package src.mock.tomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

//import src.mock.tomcat.MockRequest;
// import src.mock.tomcat.MockResponse;
// import src.mock.tomcat.MockServlet;
// import src.mock.tomcat.ServletMapping;
// import src.mock.tomcat.ServletMappingConfig;

public class MockTomcat {
    private int port=8080;
    private Map<String,String> urlServletMap=new HashMap<String,String>();
    public MockTomcat(int port){
        this.port=port;
    }
    public void start(){
        //初始化URL与对应处理的Servlet的关系
        initServletMapping();
        ServerSocket serverSocket=null;
        try{
            serverSocket=new ServerSocket(port);
            System.out.println("MockTomcat is Starting");
            while(true){
                Socket socket=serverSocket.accept();
                InputStream inputStream=socket.getInputStream();
                OutputStream outputStream=socket.getOutputStream();

                MockRequest mockRequest=new MockRequest(inputStream);
                MockResponse mockResponse=new MockResponse(outputStream);
                //请求分发
                dispatch(mockRequest,mockResponse,socket);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(serverSocket!=null){
                try{
                    serverSocket.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }

    }
    /**初始化Servlet与url匹配*/
    public void initServletMapping(){
        for(ServletMapping servletMapping:ServletMappingConfig.servletMappingList){
            urlServletMap.put(servletMapping.getUrl(),servletMapping.getClazz());
        }

    }
    /**分发请求*/
    public void dispatch(MockRequest mockRequest,MockResponse mockResponse,Socket socket){
        String clazz=urlServletMap.get(mockRequest.getUrl());
        if(clazz!=null){
            new Thread(()->{try{
                Class<MockServlet> mockServletClass=(Class<MockServlet>)Class.forName(clazz);
                MockServlet mockServlet=mockServletClass.newInstance();
                mockServlet.service(mockRequest,mockResponse);
                socket.close();
            }catch(Exception e){
                e.printStackTrace();

            }}).start();
        }else{
            try{
                mockResponse.write("404");
                socket.close();
            }catch(IOException e){
                e.printStackTrace();
            }

        }
    }
    public static void main(String[] args){
        new MockTomcat(8080).start();
    }
}
